{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "test_size = 256\n",
    "\n",
    "def init_weights(shape):\n",
    "    return tf.Variable(tf.random_normal(shape, stddev=0.01))\n",
    "\n",
    "def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden):\n",
    "    l1a = tf.nn.relu(tf.nn.conv2d(X, w,                       # l1a shape=(?, 28, 28, 32)\n",
    "                        strides=[1, 1, 1, 1], padding='SAME'))\n",
    "    l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1],              # l1 shape=(?, 14, 14, 32)\n",
    "                        strides=[1, 2, 2, 1], padding='SAME')\n",
    "    l1 = tf.nn.dropout(l1, p_keep_conv)\n",
    "\n",
    "    l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,                     # l2a shape=(?, 14, 14, 64)\n",
    "                        strides=[1, 1, 1, 1], padding='SAME'))\n",
    "    l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1],              # l2 shape=(?, 7, 7, 64)\n",
    "                        strides=[1, 2, 2, 1], padding='SAME')\n",
    "    l2 = tf.nn.dropout(l2, p_keep_conv)\n",
    "\n",
    "    l3a = tf.nn.relu(tf.nn.conv2d(l2, w3,                     # l3a shape=(?, 7, 7, 128)\n",
    "                        strides=[1, 1, 1, 1], padding='SAME'))\n",
    "    l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1],              # l3 shape=(?, 4, 4, 128)\n",
    "                        strides=[1, 2, 2, 1], padding='SAME')\n",
    "    l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]])    # reshape to (?, 2048)\n",
    "    l3 = tf.nn.dropout(l3, p_keep_conv)\n",
    "\n",
    "    l4 = tf.nn.relu(tf.matmul(l3, w4))\n",
    "    l4 = tf.nn.dropout(l4, p_keep_hidden)\n",
    "\n",
    "    pyx = tf.matmul(l4, w_o)\n",
    "    return pyx\n",
    "\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n",
    "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n",
    "trX = trX.reshape(-1, 28, 28, 1)  # 28x28x1 input img\n",
    "teX = teX.reshape(-1, 28, 28, 1)  # 28x28x1 input img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "X = tf.placeholder(\"float\", [None, 28, 28, 1])\n",
    "Y = tf.placeholder(\"float\", [None, 10])\n",
    "\n",
    "w = init_weights([3, 3, 1, 32])       # 3x3x1 conv, 32 outputs\n",
    "w2 = init_weights([3, 3, 32, 64])     # 3x3x32 conv, 64 outputs\n",
    "w3 = init_weights([3, 3, 64, 128])    # 3x3x32 conv, 128 outputs\n",
    "w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs\n",
    "w_o = init_weights([625, 10])         # FC 625 inputs, 10 outputs (labels)\n",
    "\n",
    "p_keep_conv = tf.placeholder(\"float\")\n",
    "p_keep_hidden = tf.placeholder(\"float\")\n",
    "py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)\n",
    "\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))\n",
    "train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\n",
    "predict_op = tf.argmax(py_x, 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Launch the graph in a session\n",
    "with tf.Session() as sess:\n",
    "    # you need to initialize all variables\n",
    "    tf.global_variables_initializer().run()\n",
    "\n",
    "    for i in range(100):\n",
    "        training_batch = zip(range(0, len(trX), batch_size),\n",
    "                             range(batch_size, len(trX)+1, batch_size))\n",
    "        for start, end in training_batch:\n",
    "            sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],\n",
    "                                          p_keep_conv: 0.8, p_keep_hidden: 0.5})\n",
    "\n",
    "        test_indices = np.arange(len(teX)) # Get A Test Batch\n",
    "        np.random.shuffle(test_indices)\n",
    "        test_indices = test_indices[0:test_size]\n",
    "\n",
    "        print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==\n",
    "                         sess.run(predict_op, feed_dict={X: teX[test_indices],\n",
    "                                                         Y: teY[test_indices],\n",
    "                                                         p_keep_conv: 1.0,\n",
    "                                                         p_keep_hidden: 1.0})))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
